<template>
  <div>
    <div class="flex justify-center items-center">
      <div>{{ name }}</div>
      <div class="ml-2 mr-2">
        <TreeSelect
          class="w-50"
          :tree-data="treeData"
          :field-names="{ label: 'name', value: 'code', key: 'code' }"
          :show-search="true"
          treeNodeFilterProp="name"
          v-model:value="selectTypeCode"
        />
      </div>
      <div class="mr-2">
        <a-button @click="handleApply">套用</a-button>
      </div>
      <div>
        <a-button @click="handleDesign">设计</a-button>
      </div>
    </div>
    <div style="height: calc(100vh - 200px); overflow: auto">
      <EditFlowChart :typeCode="typeCode" :editable="false" v-if="isShow" />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { computed, onMounted, ref, h, unref, onUnmounted } from 'vue';
  import { TreeSelect } from 'ant-design-vue';
  import EditFlowChart from './modules/EditFlowChart.vue';
  import { useRouter } from 'vue-router';
  import { getToken } from '/@/utils/auth';
  import { getFlowGetDirTreeAll, getAdminApplyWorkflow } from '/@/api/flowManage/flowManage';
  import { TreeItem } from '/@/components/Tree';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();

  const title = ref('流程图');
  const props = defineProps({
    activeKey: {
      type: String,
      default: '',
    },
    currentRecord: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  const { createMessage, createConfirm } = useMessage();
  const { resolve, currentRoute } = useRouter();
  const typeCode = computed(() => props.currentRecord.code);
  const name = computed(() => props.currentRecord.name);
  const selectTypeCode = ref('');
  const isShow = ref(true);

  //设计
  const handleDesign = () => {
    let routeUrl: any = {};
    console.log('props.currentRecord', props.currentRecord);
    routeUrl = resolve({
      path: '/designViewPage',
      query: {
        type: 'flow',
        typeCode: typeCode.value,
        pageName: currentRoute.value.meta.title,
        name: props.currentRecord.name,
        formCode: props.currentRecord.formCode,
        token: getToken() as any,
      },
    });
    const height = screen.height;
    const width = screen.width;
    console.log({
      routeUrl,
      height,
      width,
    });
    window.open(
      routeUrl.href,
      '',
      `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
    );
  };

  const treeData = ref<TreeItem[]>([]);
  const fetch = async () => {
    const data = (await getFlowGetDirTreeAll()) || [];
    treeData.value = setChildren(data);
  };

  function setChildren(node) {
    node.forEach((item) => {
      item.key = item.code;
      item.value = item.code;
      item.title = item.name;
      item.disabled = item.layer == 3 ? false : true;
      if (item.children && Array.isArray(item.children) && item.children.length > 0) {
        item.isLeaf = false;
        setChildren(item.children);
      } else {
        item.isLeaf = true;
      }
    });
    return node;
  }
  onMounted(() => {
    fetch();
    document.addEventListener('visibilitychange', visibilitychangecCallback);
  });
  onUnmounted(() => {
    document.removeEventListener('visibilitychange', () => {});
  });
  const visibilitychangecCallback = () => {
    // 用户息屏、或者切到后台运行 （离开页面）
    if (document?.visibilityState === 'hidden') {
      console.log('hidden');
    }
    // 用户打开或回到页面
    if (document?.visibilityState === 'visible') {
      console.log('页面可见');
      handleIsShow();
    }
  };
  const handleIsShow = () => {
    isShow.value = false;
    setTimeout(() => {
      isShow.value = true;
    }, 200);
  };

  const handleApply = () => {
    if (!unref(selectTypeCode)) {
      return createMessage.warning('请选择流程');
    }
    createConfirm({
      iconType: 'info',
      title: () => h('span', t('common.prompt')),
      content: () => h('span', '套用流程时同时附带事件脚本么'),
      maskClosable: true,
      closable: true,
      okText: '是',
      cancelText: '否',
      onOk: async () => {
        await getAdminApplyWorkflow({
          typeCode: unref(typeCode),
          templateCode: unref(selectTypeCode),
          isWithScript: true,
        });
        createMessage.success(t('common.opSuccess'));
        handleIsShow();
      },
      onCancel: async () => {
        await getAdminApplyWorkflow({
          typeCode: unref(typeCode),
          templateCode: unref(selectTypeCode),
          isWithScript: false,
        });
        createMessage.success(t('common.opSuccess'));
        handleIsShow();
      },
    });
  };
</script>
